package com.explorati.LeetCode27.removeElement;

/**
 * 给定一组数组，和一个值，删除数组中等于这个值的所有元素，然后返回数组长度 Given nums = [0,1,2,2,3,0,4,2], val = 2,
 * 
 * Your function should return length = 5, with the first five elements of nums
 * containing 0, 1, 3, 0, and 4.
 * 
 * Note that the order of those five elements can be arbitrary.
 * 
 * It doesn't matter what values are set beyond the returned length.
 * 
 * @author explorati
 *
 */
public class Solution {
	public static int removeElement(int[] nums, int val) {
		// if(nums == null){
		// return 0;
		// }

		// i指着第一个元素为val的位置，即需删除元素位置
		int i = 0;
		for (int j = 0; j < nums.length; j++) {
			// 如果j的值不等于val，将其和第一个需删除元素的位置交换
			if (nums[j] != val) {
				if (i != j) {
					swap(nums, i++, j);
				} else {
					i++;
				}
			}
			// 如果值等于val，那么j++就好
		}

		return i;
	}

	public static void swap(int[] arr, int i, int j) {
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}

	public static void main(String[] args) {
		int[] arr = { 0, 1, 2, 2, 3, 0, 4, 2 };
		removeElement(arr, 2);
		for (int i : arr) {
			System.out.print(i + "  ");
		}
	}
}
